import Taro from '@tarojs/taro'
import {ServerUserInfo, ShareInfo, UserIdentity, WxUserInfo} from './server.interface'
import {http} from './http'
import {
  CHECK_USER_INFO,
  GET_MP_KEY,
  H5_LOGIN,
  IDENTITY,
  LOGIN_URL,
  SHARE_INFO,
  IDENTITY_IS_SELLER,
  DEFAULT_SELLER_LOGIN,
  GET_INIT_CODE, TARO_ENV, LOGIN_URL_TT
} from '../constants/api'
import {GetRequest, getTempSellerId, setTempSellerId, getTokenFromCookies, replaceUrl, setStorageSync, getStorageSync} from "./tools";
import {lxH5Wx} from "./lx.h5.service";

class User {
  code = ''
  anonymousCode = ''
  token = ''
  selected = 0
  userInfo: WxUserInfo & ServerUserInfo
  bindSellerId: any = 0
  shareInfo: any
  isLogin = false
  isUserData = false
  isUserTime = 0
  userData: UserIdentity | boolean
  timeId
  router

  async getUserData() {
    this.userData = await http.get(IDENTITY, {})
    return this.userData;
  }

  async setUserData() {
    if (await this.checkLogin()) {
      const identity = await http.get<UserIdentity>(IDENTITY, {});
      if (identity) {
        this.userData = identity
        return this.userData
      } else {
        return false
      }
    } else {
      await this.jumpLogin()
      return false
    }
  }

  vcNull(filed) {
    if (filed === undefined || filed === null || filed === 'null' || !filed) {
      return ''
    }
    return filed
  }

  async mpKeyCheckLogin(newMpKey = '', category = 0, productUuid = '') {
    if (process.env.NODE_ENV === 'development') {
      return
    }
    const that = this
    clearTimeout(that.timeId)
    that.timeId = setTimeout(async () => {
      const query: any = Taro.getCurrentInstance().router.params || {};
      if (!newMpKey && query.mpkey) {
        newMpKey = query.mpkey
      }
      if (document.location.pathname === '/pay/success' || query.pkeys) {
        return
      }
      let _referer = encodeURIComponent(window.location.href);
      if (process.env.P_ENV === 'lx') {
        if (TARO_ENV === 'h5' && !lxH5Wx.getTokenFromCookies()) {
          const initCode = await http.carGet(GET_INIT_CODE)
          lxH5Wx.getRequestCode(initCode, true)
        }
        return false
      }
      const data = await http.HGet(GET_MP_KEY, {newMpKey, category, productUuid, referer: _referer})
      if (data && data.data) {
        const res = data.data
        const mpkey = this.vcNull(res.mpkey)
        const sKey = this.vcNull(res.skey)
        const storageSkey = getStorageSync('sKey') || ''
        if (mpkey) {
          const extConfig = getStorageSync('user');
          if (extConfig) {
            extConfig.mpkey = mpkey
            setStorageSync('user', extConfig)
          }
        }
        if (sKey) {
          setStorageSync('sKey', sKey)
        }
        if (res.isUseLogin) {
          await Taro.showLoading({title: '加载中...'})
          return window.location.reload()
        } else {
          if (!storageSkey && sKey) {
            return window.location.reload()
          }
        }
        if (!getTokenFromCookies(document.cookie) && query.defaultSellerLogin && query.defaultSellerLogin === '1') {
          if (window.location.href.indexOf('mpkey') > -1 && mpkey) {
            const href = window.location.href
            _referer = encodeURIComponent(replaceUrl(href, 'mpkey', mpkey || ''));
          }
          _referer = encodeURIComponent(decodeURIComponent(_referer).replace(/defaultSellerLogin/g, 'defaultSellerLoginDone'))
          let urlHref = window.location.origin + DEFAULT_SELLER_LOGIN + '?referer=' + _referer + "&t=" + new Date().getTime() + '&pkey=' + (query.pkey || '')
          if (mpkey) {
            urlHref = urlHref.replace('mpkey', 'mpkeyno')
            urlHref = urlHref + '&mpkey=' + mpkey
          }
          window.location.replace(urlHref)
        }
      }
      return false
    }, 200)
  }

  async jumpLogin(delta?) {
    Taro.hideLoading()
    if (process.env.TARO_ENV === 'h5') {
      if (process.env.P_ENV === 'lx') {
        const query: any = Taro.getCurrentInstance().router.params;
        const user = getStorageSync('user')
        const token = getTokenFromCookies(document.cookie)
        if (!token || (!user || query.mpkey)) {
          if (document.location.pathname !== '/pay/success' && !query.pkeys) {
            await this.mpKeyCheckLogin(query.mpkey, 0 , '')
          }
        }
      } else {
        const _referer = encodeURIComponent(window.location.href);
        const hostname = window.location.hostname;
        let mpkey = ''
        const user = getStorageSync('user') || ''
        if (user && user.mpkey && user.mpkey !== 'undefined' && user.mpkey != null) {
          mpkey = user.mpkey
        }
        let urlHref = 'http://' + hostname + '/' + H5_LOGIN + '?referer=' + _referer + "&t=" + new Date().getTime();
        if (mpkey) {
          urlHref += '&mpkey=' + mpkey
        }
        if (window.location.pathname !== '/main/login/login' && window.location.pathname !== '/common/tools/index') {
          await Taro.showLoading({title: '加载中...'})
          window.location.replace(window.location.origin + '/main/login/login?jumpUrl=' + urlHref)
        }
      }
    } else {
      let url = '/main/login/login';
      if(delta !== undefined && delta !== null && delta !== "" && delta !== 0 && delta !== "0") {
        url += `?delta=${delta}`;
      }
      const pages = Taro.getCurrentPages();
      const currPage = pages[pages.length - 1];
      if (currPage.route === 'main/login/login') {
        return false
      }
      await Taro.navigateTo({
        url
      })
    }
  }

  async checkLogin() {
    try {
      // 如果是 H5
      if (process.env.TARO_ENV === 'h5') {
        const query: any = Taro.getCurrentInstance().router.params
        if (query && process.env.P_ENV !== 'lx') { // 灵锡无分销商 pc 端
          const {sellerId = '', bindSellerId = ''} = query
          sellerId && setStorageSync('sellerId', sellerId)
          bindSellerId && setStorageSync('bindSellerId', bindSellerId)
          // 如果是从分销商过来的强制替换代码 pc_seller
          if (query.pc_seller && query.token) {
            this.token = query.token
            this.isLogin = true
            setStorageSync('user', query)
            return true
          }
        }
        if (query.pkeys) { // 后台预览或其它场景参数上携带 pkeys 使用 参数上的 pkeys 为 平台 uuid
          query.pkey = query.pkeys
          setStorageSync('user', query)
          return false
        }
        let user = getStorageSync('user') || ''
        if (query && query.pkey) {
          if (!user) {
            user = query
            setStorageSync('user', query)
          } else if (user && !user.pkey) {
            user.pkey = query.pkey
            setStorageSync('user', user)
          }
        }
        const token = getTokenFromCookies(document.cookie)
        if (process.env.P_ENV === 'lx') {
          if (token) {
            if (!user && query) {
              this.isLogin = true
              setStorageSync('user', query)
            }
            user = getStorageSync('user')
            if ((query.pkey || query.pkeys) && user && !user.pkey) {
              this.isLogin = true
              user.pkey = query.pkey || query.pkeys
              setStorageSync('user', user)
            }
            user = getStorageSync('user')
            if (!user.pkey && document.location.pathname != '/pay/success' && !query.pkeys) {
              await this.mpKeyCheckLogin(query.mpkey || '')
            }
            return true
          } else { // 如果 cookie 里没有 token，跳转登录
            await this.jumpLogin();
            return false
          }
        } else {
          if (query.mpkey || query.defaultSellerLoginDone === '1' || query.defaultSellerLogin === '1') {
            await this.mpKeyCheckLogin()
          }
          if ((!user || !user.pkey || user.pkey === 'null') && document.location.pathname !== '/other/debug/index' && document.location.pathname !== '/other/debug/open' && document.location.pathname !== '/common/tools/index' && document.location.pathname !== '/pay/success' && !query.pkeys && !user.pkeys) {
            const href = window.location.href
            const referer = encodeURIComponent(href);
            window.location.replace(window.location.origin + '/msvc-shop/v1/mp/user/pkey?referer=' + referer)
            return false
          }
          return token;
        }
      } else {
        const userInfo = getStorageSync('user')
        if (userInfo.token && !userInfo.requestToken) {
          this.userInfo = userInfo.userInfo
          this.token = userInfo.token
          this.isLogin = true
          return true
        } else {
          this.logout()
          return false
        }
      }
    } catch (e) {
      this.logout()
      return false
    }
  }

  async doLogin(userSecretInfo): Promise<false | WxUserInfo & ServerUserInfo> {
    return new Promise(async resolve => {
      const data = {
        code: this.code,
        ...userSecretInfo.userInfo,
        bindSellerId: this.bindSellerId,
        itemUUID: '',
        path: ''
      }
      let userInfo
      let api = LOGIN_URL
      let method = 'post'
      if (process.env.TARO_ENV === 'tt') {
        method = 'carGet'
        api = LOGIN_URL_TT
      }
      if (process.env.TARO_ENV === 'weapp' || process.env.TARO_ENV === 'tt') {
        userInfo = await http[method]<ServerUserInfo>(api, data)
      }
      if (userInfo.uuid) {
        setStorageSync('randomUuid', userInfo.uuid)
      }
      this.code = ''
      this.anonymousCode = ''
      if (userInfo && userInfo.token) {
        this.token = userInfo.token
        const userData = {...userSecretInfo.userInfo, ...userInfo}
        this.userInfo = userData
        resolve(userData)
      } else if (userInfo) {
        resolve(userInfo)
      } else {
        resolve(false)
      }
    })
  }

  logout() {
    try {
      this.token = ''
      this.isLogin = false
      if (process.env.TARO_ENV === 'weapp' || process.env.TARO_ENV === 'tt') {
        this.userInfo = {
          nickName: '',
          avatarUrl: '',
          gender: 0,
          country: '',
          province: '',
          city: '',
          language: '',
          indexShowType: 1,
          loginSession: '',
          openId: '',
          platformTelephone: '',
          sellerTelephone: '',
          serviceTelephoneType: 0,
          token: '',
          status: ''
        }
        this.anonymousCode = ''
        this.shareInfo = false
      }
      Taro.removeStorageSync('user')
    } catch (e) {
      console.log('logout', e)
    }
  }

  async checkUserInfo() {
    const res = await http.get(CHECK_USER_INFO, {})
    if (res) {
      return res
    } else {
      return false
    }
  }

  async serverLogin() {
    return new Promise<boolean>(resolve => {
      Taro.login().then(async code => {
        this.code = code.code
        const wxPhone = getStorageSync('wxPhone')
        if (wxPhone) {
          const loginParam = {
            nickName: '',
            gender: 1,
            language: '',
            city: '',
            province: '',
            country: '',
            avatarUrl: '',
            bindSellerId: 0,
            itemUUID: '',
            path: '',
          }
          const ret = await this.doLogin(loginParam)
          if (ret && ret.token) {
            user.token = ret.token
            const userData = {...ret, ...loginParam}
            user.userInfo = userData
            user.isLogin = true
            setStorageSync('user', {token: ret.token, userInfo: userData,})
          } else {
            this.logout()
            resolve(false)
          }
        } else {
          Taro.getUserInfo({}).then(async (userInfo) => {
            const ret = await this.doLogin(userInfo)
            if (ret && ret.token) {
              this.token = ret.token
              const userData = {...ret, ...userInfo}
              this.userInfo = userData
              this.isLogin = true
              setStorageSync('user', {token: ret.token, userInfo: userData})
              resolve(true)
            } else {
              this.logout()
              resolve(false)
            }
          }).catch(() => {
            this.logout()
            resolve(false)
          })
        }
      }).catch(err => {
        this.logout()
        resolve(false)
        console.log('serverLogin-login-err', err)
      })
    })
  }

  async getSellerParam(tempSellerId = '') {
    if (process.env.TARO_ENV === 'tt') {
      return new Promise<string>(async (resolve) => {
        resolve('')
      })
    }
    if (!tempSellerId) {
      tempSellerId = getTempSellerId()
    }
    return await http.get<ShareInfo>(SHARE_INFO, {tempSellerId})
  }

  async getShareParams(tempSellerId = '') {
    if (process.env.TARO_ENV === 'tt') {
      return new Promise<string>(async (resolve) => {
        resolve('')
      })
    }
    if (!tempSellerId) {
      tempSellerId = getTempSellerId()
    }
    const ret: any = await http.get<ShareInfo>(SHARE_INFO, {tempSellerId})
    if (ret) {
      return `sellerId=${ret.sellerId || ''}&bindSellerId=${ret.bindSellerId || ''}&tempSellerId=${ret.tempSellerId || ''}`
    }
    return ''
  }

  async getSellerParams(tempSellerId = '') {
    if (process.env.TARO_ENV === 'tt') {
      return new Promise<string>(async (resolve) => {
        resolve('')
      })
    }
    if (!tempSellerId) {
      tempSellerId = getTempSellerId()
    }
    return new Promise<string>(async (resolve) => {
      if (await this.checkLogin()) {
        let identityIsSeller
        if (process.env.DISTINGUISH_IDENTITY) {
          identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
        }
        if (identityIsSeller && !identityIsSeller.isSeller && process.env.P_ENV === 'kd') { // 不是分销商不携带分享参数   佣金问题
          resolve('force_platform_seller=1')
        }
        const ret = await http.get<ShareInfo>(SHARE_INFO, {tempSellerId})
        if (ret) {
          this.shareInfo = ret
          let url = ''
          if (this.shareInfo.sellerId) {
            url += `sellerId=${this.shareInfo.sellerId || ''}`
          }
          if (this.shareInfo.bindSellerId) {
            url += `&bindSellerId=${this.shareInfo.bindSellerId || ''}`
          }
          if (this.shareInfo.tempSellerId) {
            url += `&tempSellerId=${this.shareInfo.tempSellerId || ''}`
          }
          resolve(url)
        } else {
          resolve('')
        }
      } else {
        resolve('')
      }
    })
  }

  async getMovieSellerParams(tempSellerId = '') {
    if (process.env.TARO_ENV === 'tt') {
      return new Promise<string>(async (resolve) => {
        resolve('')
      })
    }
    if (!tempSellerId) {
      tempSellerId = getTempSellerId()
    }
    return new Promise<string>(async (resolve) => {
      if (await this.checkLogin()) {
        const userIdentity = await http.get(IDENTITY, {})
        if (!userIdentity.isSeller && process.env.P_ENV === 'kd') { // 不是分销商不携带分享参数   佣金问题
          resolve('force_platform_seller=1')
        }
        const ret = await http.get<ShareInfo>(SHARE_INFO, {tempSellerId})
        if (ret) {
          this.shareInfo = ret
          let url = ''
          if (this.shareInfo.sellerId) {
            url += this.shareInfo.sellerId || ''
          }
          if (this.shareInfo.bindSellerId) {
            url += `_${this.shareInfo.bindSellerId || ''}`
          }
          if (this.shareInfo.tempSellerId) {
            tempSellerId = `${this.shareInfo.tempSellerId || ''}`
            url += `_${this.shareInfo.tempSellerId || ''}`
          }
          setTempSellerId(tempSellerId)
          resolve(url)
        } else {
          resolve('')
        }
      } else {
        resolve('')
      }
    })
  }
}

export const user = new User()
